package com.vectquant.lwwl_service01.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vectquant.lwwl_service01.config.WechatConfig;
import com.vectquant.lwwl_service01.util.WechatDecryptUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务工具类
 * 处理与微信服务器的交互
 */
@Service
public class WechatService {
    private final WechatConfig wechatConfig;
    private final ObjectMapper objectMapper;
    public WechatService(WechatConfig wechatConfig,ObjectMapper objectMapper){
        this.wechatConfig = wechatConfig;
        this.objectMapper = objectMapper;
    }
    /**
     * 通过code获取openid和session_key
     * @param code小程序前端传来的code
     * @return包含openid和session_key的map
     */
    public Map<String,String> getOpenidByCode(String code){

            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wechatConfig.getAppid() +
                    "&secret=" + wechatConfig.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet httpGet = new HttpGet(url);
                HttpResponse response = httpClient.execute(httpGet);
                String responseStr = EntityUtils.toString(response.getEntity());
//           解析微信返回的json数据
                Map<String, String> result = objectMapper.readValue(responseStr, HashMap.class);
                if (result.containsKey("openid")) {
                    return result;
                } else {
                    throw new RuntimeException("获取openid失败：" + result.get("errmsg"));
                }
            } catch (Exception e) {
                throw new RuntimeException("请求微信API失败", e);
            }
    }
    /**
     * 解密手机号
     * @param sessionkey 会话密钥
     * @param encryptedData 加密数据
     * @param iv 初始向量
     * @return 解密后的手机号
     */
    public String decryptPhoneNumber(String sessionkey,String encryptedData,String iv){
        try{
/**
 * 这里需要实现微信加密数据的解密算法
 * 由于微信解密算法比较复杂，这里使用伪代码表示*/
            String decrytedData = WechatDecryptUtil.decrypt(encryptedData,sessionkey,iv);
//            解析json获取手机号
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String,Object> data = objectMapper.readValue(decrytedData,HashMap.class);
            return (String) data.get("phoneNumber");
        }catch (Exception e){
            throw new RuntimeException("解密手机号失败",e);
        }
    }
    /**
     * 通过code获取access_token
     * @return access_token
     */
    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + wechatConfig.getAppid() +
                "&secret=" + wechatConfig.getSecret();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            String responseStr = EntityUtils.toString(response.getEntity());

            // 解析微信返回的json数据
            Map<String, Object> result = objectMapper.readValue(responseStr, HashMap.class);

            if (result.containsKey("access_token")) {
                return (String) result.get("access_token");
            } else {
                throw new RuntimeException("获取access_token失败：" + result.get("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求微信API失败", e);
        }
    }
    /**
     * 新增方法：通过phoneCode获取手机号（新版本接口）
     * @param phoneCode 前端通过getPhoneNumber事件获取的code
     * @return 手机号
     */
    public String getPhoneNumberByCode(String phoneCode) {
        // 1. 获取access_token
        String accessToken = getAccessToken();

        // 2. 调用微信API获取手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");

            // 设置请求体
            String requestBody = "{\"code\": \"" + phoneCode + "\"}";
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            String responseStr = EntityUtils.toString(response.getEntity());

            // 解析响应
            Map<String, Object> result = objectMapper.readValue(responseStr, HashMap.class);

            if (result.containsKey("errcode") && (Integer) result.get("errcode") == 0) {
                // 提取手机号信息
                Map<String, Object> phoneInfo = (Map<String, Object>) result.get("phone_info");
                return (String) phoneInfo.get("purePhoneNumber");
            } else {
                throw new RuntimeException("获取手机号失败：" + result.get("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求微信API失败", e);
        }
    }
}
